const WXAPI = require('../../wxapi/main')
const app = getApp();
const regeneratorRuntime = require('../../utils/runtime')
const dateUtil = require('../../utils/date.js')

import Toast from 'tdesign-miniprogram/toast/index';

Page({
  data: {
    venueDetail: {
    },
    fabButton: {
      icon: 'call',
      openType: 'getPhoneNumber',
    },
    isYYNightOrder: false,
    isAfterNoomOrder: false,
    session: 1,
    visible: false,
    isReadTip: false,
    calendarVisible: false,
    date: null,
    showDate: null,
    minDate: null,
    maxDate: null,
    venuePriceMap: {},
    canUseCoupons: [],
    coupons_current_no: 0,
    coupons_page_size: 10,
    isLastPage: false,
    couponVisible: false,
    use_coupon: '',
    selectedCoupon: null,
    confirmCoupon: null,
    remark: "",
    userInfo: {},
    themeColor: app.globalData.themeColor,
    sessionVisible:false,
    sessionOptions:[],
    sessionShow:"",
    interval:null,
  },
  watch: {

    date: function (_this, newValue) {
      // const date = new Date(newValue);
      // const year = date.getFullYear();
      // var month = date.getMonth() + 1
      // var day = date.getDate();
      const format = (val) => {
        const date = new Date(val);
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
      };
      _this.setData({
        showDate: format(newValue)
      });
    }

  },
  tapBanner(e){
    wx.previewImage({
      current: e.currentTarget.dataset.data, // 当前显示图片的链接，不填则默认为 urls 的第一张
      urls: this.data.venueDetail.background_pic_list // 需要预览的图片链接列表
    })
  },
  confirmCoupon() {
    // 把选中的券名字显示在上面
    var { selectedCoupon } = this.data;
    if(selectedCoupon){
      this.setData({
        use_coupon: selectedCoupon.coupon_name,
        confirmCoupon: selectedCoupon,
        couponVisible: false,
        visible: true
      })
    }else{
      this.setData({
        use_coupon: '',
        confirmCoupon: null,
        couponVisible: false,
        visible: true
      })
    }
    
  },
  onSelectCoupon(e) {
    const data = e.currentTarget.dataset.data;
    if(data.is_not_valid){
      wx.showToast({
        "title":"当前卡券不可用"
      });  
      return;
    }
    if(this.data.selectedCoupon && data.id==this.data.selectedCoupon.id){
      //取消
      this.setData({
        selectedCoupon: null
      });
      return;
    }
    this.setData({
      selectedCoupon: data
    });
  },
  openCouponList() {
    if (this.data.canUseCoupons.length == 0) {
      return;
    }
    this.setData({
      selectedCoupon: this.data.confirmCoupon,
      couponVisible: true,
      visible: false
    })

  },
  closeCouponListPop() {
    this.setData({
      couponVisible: false,
      visible: true
    })
  },
  onSessionPicker(){
    this.setData({
      sessionVisible: true,
    })
  },
  goPay() {
    
    let isReadTip = this.data.isReadTip;
    if (!isReadTip) {
      return;
    }
    var { remark, userInfo, venueDetail, selectedCoupon, session, showDate ,venuePriceMap,} = this.data;
    var param = {
      user_id: userInfo.id,
      wx_no: userInfo.wx_no,
      venue_id: venueDetail.id,
      remark,
      session,
      date: showDate
    }
    if (selectedCoupon && selectedCoupon.id != null)
      param.coupon_id = selectedCoupon.id
    var payment_method=1
    //TODO 调用微信支付接口
     if(userInfo.recharge_balance && userInfo.recharge_balance>venuePriceMap[session].price)
      payment_method=4
    debugger
    WXAPI.appoint(venueDetail.id, param,{payment_method}).then(res => {
      
      if(res.code!=200){
        Toast({
          context: this,
          selector: '#t-toast',
          message: "预约异常:"+(res.message||res.msg),
          theme: 'error',
          direction: 'column',
        });
        return
      }
      var payment=res.data;
      if (!payment){
        wx.showToast({
          "title":"预约成功"
        });        
        return;
      }
      wx.requestPayment({
        appid: payment.appid,
        timeStamp: payment.timeStamp,
        nonceStr: payment.nonceStr,
        package: payment.package,
        signType: payment.signType,
        paySign: payment.paySign,
        success:(res)=> {
          wx.showToast({
            "title":"支付成功"
          });        },
        fail:(res)=> {
          console.log(res)
          wx.showToast({
            icon:"none",
            "title":"支付取消"
          });  
          clearInterval(this.data.interval)

        }
      })
      var interval=setInterval(()=>{
        WXAPI.queryOrderByNo(payment.order_no).then(res=>{
          if(res.status==2){
           clearInterval(this.data.interval)
           app.refreshData((userInfo)=>{
            this.setData({
              userInfo
            })
          });
           setTimeout(()=> {
            wx.navigateTo({
              url: "/pages/appointment/index"
            })
          }, 1000)
          }
       })
      },100)
      this.setData({
         interval
      })
      

    })



  },


  sessionConfirm(e) {
    const { value,text,disabled } = e.detail.value;
    if(disabled){
      Toast({
        context: this,
        selector: '#t-toast',
        message: '无法选中，已被预约',
        theme: 'warning',
        direction: 'column',
      });
      return
    }
    this.setData({
      session:value,
      sessionShow:text,
      sessionVisible:false
    })
  },
  sessionPickerCancel(){
    this.setData({
       sessionVisible:false
    })
  },
  onLoad(e) {

    getApp().setWatcher(this); // 设置监听器


    this.setData({
      venueDetail: JSON.parse(decodeURIComponent(e.data)),
      userInfo: wx.getStorageSync("userInfo")

    })
    
    const now = new Date();

    // 转换为 yyyy-mm-dd 的格式
    const year = now.getFullYear();
    const month = now.getMonth() + 1;
    const day = now.getDate();
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    const d7ays = new Date();
    d7ays.setDate(d7ays.getDate() + 7);

    // 不同会员有不同的预约时间
    const format = (val) => {
      const date = new Date(val);
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
    };
    this.setData({
      minDate: tomorrow.getTime(),
      maxDate: this.data.userInfo.vip?d7ays.getTime():tomorrow.getTime(),
      date: tomorrow.getTime(),
      showDate: format(tomorrow)
    })
    this.queryAppiontment(format(tomorrow));
    WXAPI.queryVenuePrice(this.data.venueDetail.id).then(res=> {

      var info = res;
      var venuePriceMap = {};
      var sessionOptions=[];

      info.forEach(item => {
        venuePriceMap[item.type] = item;
        if(item.type>2){
          return
        }
        sessionOptions.push({
          value:item.type,
          text:`${item.type==1?'下午场':'夜晚场'}(${item.begin_hour}:00-${item.end_hour}:00)`
       })
      });
      sessionOptions.sort(function(item1, item2) {
        return item1.type > item2.type;
      });

      var sesionJson=venuePriceMap[this.data.session];
      this.setData({
        venuePriceMap,
        sessionOptions,
        sessionShow:`${sesionJson.type==1?'下午场':'夜晚场'}(${sesionJson.begin_hour}:00-${sesionJson.end_hour}:00)`
      })

      wx.hideNavigationBarLoading();
    }).catch((e) => {
      wx.hideNavigationBarLoading();
    });

    this.queryCanUseCoupon();

  },
  loadMoreCoupons() {
    let { coupons_current_no, coupons_page_size } = this.data;
    this.setData({
      coupons_current_no: coupons_current_no + coupons_page_size
    })
    this.queryCanUseCoupon();
  },
  
  /**
   * 根据日期查询当日预约情况
   */
  queryAppiontment(formattedDate){
    
    WXAPI.queryAppointment(this.data.venueDetail.id, formattedDate).then(res=> {
      var info = res;
      if (info && info.length > 0) {
        var isAfterNoomOrder=false,isYYNightOrder=false;
        info.forEach(item => {
          if (item.session == 1) {
            var sessionOptions=this.data.sessionOptions;
            sessionOptions.forEach(it=>{
               if(it.value==item.session){
                   it.disabled=true
               }
            })
            isAfterNoomOrder=true
            this.setData({
              isAfterNoomOrder: true,
              sessionOptions
            });
          } else {
            var sessionOptions=this.data.sessionOptions;
            sessionOptions.forEach(it=>{
               if(it.value==item.session){
                   it.disabled=true
               }
            })
            isYYNightOrder=true
            this.setData({
              isYYNightOrder: true,
              sessionOptions
            });
          }

        })

        if (isAfterNoomOrder && isYYNightOrder) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '当前日期已预约满了',
            theme: 'warning',
            direction: 'column',
          });
        }


      }


      wx.hideNavigationBarLoading();
    }).catch((e) => {
      wx.hideNavigationBarLoading();
    });
  },
  /**
   * 查询未使用的卡券
   * @returns 
   */
  queryCanUseCoupon() {
    ;
    let { coupons_current_no, coupons_page_size, isLastPage } = this.data;
    let _canUseCoupons=this.data.canUseCoupons
    if (isLastPage) {
      return;
    }
    //venue==3 预约结算
    WXAPI.queryCouponsByUser(this.data.userInfo.id, {
      "payment_venue": 3, "status": 1,
      "current_no": coupons_current_no,
      "page_size": coupons_page_size
    }).then(res => {
      
      var canUseCoupons = res;
      if (!canUseCoupons || canUseCoupons.length == 0) {
        this.setData({
          isLastPage: true
        })
        return;
      }
      canUseCoupons.forEach(item => {
        item.expire_time = dateUtil.toDate(item.expire_time)
        item.use_time = dateUtil.toDate(item.use_time)
        item.is_not_valid=dateUtil.compare(item.start_time,new Date());
        item.start_time = dateUtil.toDate(item.start_time)

      })
      if(_canUseCoupons!=undefined && _canUseCoupons.length>0)
      _canUseCoupons=_canUseCoupons.concat(canUseCoupons)
      else
      _canUseCoupons=canUseCoupons
      
      this.setData({
        canUseCoupons:_canUseCoupons
      })

    })
  },
  letMeKnow(){
     this.setData({
      isReadTip:!this.data.isReadTip
     })
  },
  onShow() {


  },
  onVisibleChange(e) {
    this.setData({
      visible: e.detail.visible,
    });
  },
  handleCalendar() {
    if (this.data.date == null) {
      const tomorrow = new Date();
      tomorrow.setDate(tomorrow.getDate() + 1);
      this.setData({
        date: tomorrow.getTime(),
      })
    }
    this.setData({
      calendarVisible: true
    })
  },
  handleConfirm(e) {
    const {
      value
    } = e.detail;
    const format = (val) => {
      const date = new Date(val);
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
    };
    var selectedDate=format(value)
    this.setData({
      date: new Date(value).getTime(),
      showDate: selectedDate,
    });
    this.queryAppiontment(selectedDate);
  },
  goYY: function() {

    this.setData({
      visible: true
    })
  },



})